<!-- 右侧视频列表 -->
<script setup>
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  watch,
  computed,
  nextTick,
} from "vue";
import { LoadingOutlined, EyeOutlined } from "@ant-design/icons-vue";
// 视频预览组件
import viewVideo from "@/views/shotstack/components/dialogComponent/viewVideo.vue";
// 保存文件弹窗
import MaterialsModule from "@/views/shotstack/components/MaterialsModule/index.vue";
import { nanoid } from "nanoid";
import { message } from "ant-design-vue";
import request from "@/common/utils/request";
// 路由
import { useRouter } from "vue-router";
const router = useRouter();
// 导出完成弹窗
import awaitDialog from "@/views/shotstack/components/dialogComponent/awaitDialog.vue";
const awaitModel = ref(null);

const viewVideoRef = ref(null);
const props = defineProps({
  listArr: {
    type: Array,
    default: () => {
      return [];
    },
  },
  queryData: {
    type: Object,
    default: () => {
      return {};
    },
  },
  // 加载中(此时就需要展示占位符)
  loading: {
    type: Boolean,
    default: false,
  },
  // preview接口加载中, 此时不允许点击生成更多
  previewLoading: {
    type: Boolean,
    default: false,
  },
  // 项目
  queryId: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits(["selectChange:item", "selectAll:data", "addMore"]);

const state = reactive({
  check_all: false,
  params: {
    // 保存的视频id数组
    shotstack_ids: [],
    // 保存的文件夹id
    folder_id: "",
    // 项目id
    id: "",
    // 文件夹id
    folder_id: "",
    shotstack_response_num: 0,
  },
  // 保存弹窗开关
  saveVisible: false,
  // 导出按钮 loading
  exportLoading: false,
  // 当前小眼睛预览的项
  viewItem: {},
});

// 勾选某项
const selectVideo = (item) => {
  // item.select = !item.select
  emit("selectChange", item.id);
  nextTick(() => {
    state.check_all = props.listArr.every((item) => item.select);
  });
};
// 全选反选
const selectAll = (val) => {
  console.log(val, state.check_all, "全选反选");

  nextTick(() => {
    emit("selectAll", state.check_all);
  });
};

// 勾选的视频
const select_num = computed(() => {
  return props.listArr.filter((ele) => ele.select);
});

// 生成更多
const addMore = () => {
  if (props.previewLoading) return message.warning("创建生成中, 请稍后...");
  emit("addMore");
};

// 多选导出
const handleExport = () => {
  if (select_num.value.length <= 0) message.warn("请先选择视频!");
  // 传入的视频id
  state.params.shotstack_ids = select_num.value.map((ele) => ele.id);
  // 传入数量
  state.params.shotstack_response_num = state.params.shotstack_ids.length;
  state.params.id = props.queryId.id;
  state.saveVisible = true;
};

// 选择文件夹后发起导出请求
const saveFn = async (options, id) => {
  // 文件夹id
  state.params.folder_id = id;
  state.exportLoading = true;
  const loading = message.loading("正在导出...");
  state.saveVisible = false;
  try {
    const res = await request.post(
      "/work_ai",
      `/user/shotstack/oneclick/video/save`,
      state.params
    );
    // const res = await request.put("/work_ai", `/user/shotstack/preview/high`, state.params)
    if (res?.code && res.code != 1000) throw new Error(res.msg || "保存失败!");
    awaitModel.value && awaitModel.value.showModal();
  } catch (error) {
    message.error(error.message);
  } finally {
    // 关闭loding
    loading();
    state.exportLoading = false;
    // 重置提交的数据
    resetSubmitData();
  }
};

// 预览某个视频
const toView = (item) => {
  // 存储预览的项
  state.viewItem = JSON.parse(JSON.stringify(item));
  viewVideoRef.value.open(item.video_url);
};

// 预览视频的时候 单个导出
const exportItem = () => {
  // 传入的视频id
  state.params.shotstack_ids = [state.viewItem.id];
  // 传入数量
  state.params.shotstack_response_num = 1;
  state.params.id = props.queryId.id;
  viewVideoRef.value.close();

  state.saveVisible = true;
};

const onCancel = () => {
  resetSubmitData();
  console.log(state.params, "重置之后的提交参数");
  state.saveVisible = false;
};

// 重置需要提交的数据
const resetSubmitData = () => {
  Object.assign(state.params, {
    // 保存的视频id数组
    shotstack_ids: [],
    // 保存的文件夹id
    folder_id: "",
    // 项目id
    id: "",
    // 文件夹id
    folder_id: "",
    shotstack_response_num: 0,
  });
};

// 查看成片库
const goBack = () => {
  router.push({
    name: "ComposeMaterial",
    query: {
      id: 3,
    },
  });
};

// 视频预览关闭, 清空存储的预览项
const isClose = () => {
  state.viewItem = {};
};

defineExpose({
  resetSubmitData,
});
</script>

<template>
  <div class="container">
    <h1 class="title">生成预览</h1>
    <!-- {{ props.listArr }} -->
    <template v-if="props.listArr.length || props.loading">
      <div class="task-list">
        <template v-if="props.listArr.length">
          <div
            v-for="item in props.listArr"
            class="task-card-item"
            @click="selectVideo(item)"
          >
            <!-- 勾选 -->
            <a-checkbox
              class="check_box"
              v-model:checked="item.select"
            ></a-checkbox>
            <div class="video_box">
              <!-- 预览小眼睛 -->
              <EyeOutlined class="toView" @click.stop="toView(item)">
              </EyeOutlined>
              <!-- 有封面, 优先使用封面 -->
              <template v-if="item?.poster_url">
                <img :src="item.poster_url" alt="">
              </template>

              <template v-else>
                <video class="video_player" :src="item.video_url"></video>
              </template>
              <span class="timer_box">{{ item.duration_text }}</span>
            </div>
            <div class="video_desc" v-if="item?.dec">
              <span>
                {{ item?.dec || "" }}
              </span>
            </div>
          </div>
        </template>

        <!-- 占位符数量 = 当前页数量减去已加载数量 -->
        <div
          class="loding_item"
          v-for="i in props.queryData.pageSize - props.listArr.length"
          :key="i"
        >
          <div class="loding_progress">
            <a-progress
              :percent="100"
              :showInfo="false"
              type="line"
              size="small"
              :stroke-color="{
                '0%': '#108ee9',
                '100%': '#87d068',
              }"
              status="active"
            />
          </div>
          <span class="loding_text">生成中, 预计还需2分钟</span>
          <div class="loding_dec">
            <span>
              <LoadingOutlined></LoadingOutlined>
            </span>
            <span class="loding_dec_text">正在合成视频......</span>
          </div>
        </div>

        <div class="task-card-add" @click="addMore">
          <span class="add_icon">+</span>
          <span class="add_text"> 生成更多 </span>
        </div>
      </div>
    </template>

    <template v-else>
      <div class="img_box">
        <img class="empty_img" src="../imgs/privew.webp" alt="" />
      </div>
    </template>

    <div class="bottom_box">
      <a-checkbox
        class="check_box"
        :disabled="!props.listArr.length"
        v-model:checked="state.check_all"
        @change="selectAll"
        >选择全部 &nbsp; 已选:
        <span class="select_num">{{ select_num.length }}</span></a-checkbox
      >
      <a-button
        class="btn_box"
        type="primary"
        :loading="state.exportLoading"
        :disabled="select_num.length <= 0"
        @click="handleExport"
        >导出视频</a-button
      >
    </div>
  </div>

  <!-- 视频预览 -->
  <viewVideo ref="viewVideoRef" @isClose="isClose">
    <template #isfooter>
      <a-button type="default" @click="viewVideoRef.close">关闭</a-button>
      <a-button type="primary" @click="exportItem">导出</a-button>
    </template>
  </viewVideo>

  <!-- 保存到文件夹弹窗@selfSubmit="saveVideoData"  -->
  <MaterialsModule
    ref="materials"
    jobCategory="videoSplit"
    :aisave="true"
    :requestType="true"
    :material_type="'video'"
    :isFlaking="true"
    @saveName="saveFn"
    :visible="state.saveVisible"
    @onCancel="onCancel"
  />

  <!-- 导出完成弹窗 -->
  <awaitDialog ref="awaitModel">
    <template #btns>
      <div style="display: flex; justify-content: center">
        <a-button
          class="btn"
          style="margin-right: 10px"
          @click="awaitModel.closeModal()"
          >关闭</a-button
        >
        <a-button class="btn" type="primary" @click="goBack">
          查看成片库
        </a-button>
      </div>
    </template>
  </awaitDialog>
</template>

<style lang="less" scoped>
.container {
  // 素材卡片的背景色
  @bgc: #969aa0;

  // 浅色背景
  @qianseBgc: #f8f8f9;
  padding: 15px 20px;
  border-radius: 10px;
  width: 100%;
  height: 100%;

  display: flex;
  flex-direction: column;
  gap: 10px 0;

  .title {
    font-weight: 550;
  }

  // 为空的占位图
  .img_box {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .empty_img {
      width: 30%;
      object-fit: contain;
    }
  }

  .bottom_box {
    display: flex;
    flex-direction: column;
    gap: 10px 0;

    .select_num {
      color: var(--ss-primary-color);
    }

    .btn_box {
      width: 100px;
    }
  }

  .task-list {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 20px;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }

    .task-card-item,
    .loding_item,
    .task-card-add {
      height: 220px;
      position: relative;
      overflow: hidden;
      width: 188px;
      cursor: pointer;
      border-radius: 5px;
      box-sizing: border-box;
      background: @bgc;
      display: flex;
      flex-direction: column;
    }

    // 加载中
    .loding_item {
      background-color: @qianseBgc;
      justify-content: center;
      align-items: center;
      padding: 15px;
      gap: 10px;

      .loding_progress {
        width: 100%;
      }

      .loding_text {
        font-weight: 600;
      }

      .loding_dec {
        .loding_dec_text {
          color: #9b9b9b;
          margin-left: 5px;
        }
      }
    }

    .task-card-add {
      background: @qianseBgc;
      justify-content: center;
      align-items: center;
      transition: all 0.3s;

      &:hover {
        color: var(--ss-primary-color);
      }

      .add_icon {
        font-size: 30px;
      }

      .add_text {
        font-size: 14px;
      }
    }

    // 视频卡片样式
    .task-card-item {
      justify-content: space-between;

      // hover效果
      &:hover {
        & .video_box {
          &::after {
            background: rgba(0, 0, 0, 0.3);
          }

          .toView {
            opacity: 1;
          }
        }
      }

      .check_box {
        position: absolute;
        right: 5%;
        top: 3%;
        z-index: 11;
      }

      .video_box {
        // width: 100%;
        height: 100%;
        // height: 156px;
        flex: 1;
        overflow: hidden;
        display: flex;
        justify-content: center;
        position: relative;

        img{
          height: 100%;
          width: 100%;
          object-fit: cover;
        }

        // 遮罩
        &::after {
          content: "";
          position: absolute;
          left: 0;
          top: 0;
          z-index: 3;
          width: 100%;
          height: 100%;
          background: transparent;
          cursor: pointer;
          transition: all 0.3s;
        }

        // 预览小眼睛
        .toView {
          position: absolute;
          top: 45%;
          left: 50%;
          z-index: 9;
          opacity: 0;
          transition: all 0.3s;
          font-size: 25px;
          color: #fff;
          transform: translate(-50%);
          cursor: pointer;

          &:hover {
            color: var(--ss-primary-color-hover);
          }
        }

        .video_player {
          height: 100%;
          width: 100%;
          background-color: @bgc;
        }

        .timer_box {
          position: absolute;
          display: inline-block;
          font-size: 12px;
          color: #fff;
          left: 3%;
          bottom: 3%;
        }
      }

      .video_desc {
        border-bottom-right-radius: 5px;
        padding: 5px;
        border-bottom-left-radius: 5px;
        background: rgb(244, 244, 245);
        box-sizing: border-box;

        span {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          width: auto;
          font-family: pingfang sc, -apple-system, blinkmacsystemfont, segoe ui,
            hiragino sans gb, microsoft yahei, helvetica neue, sans-serif,
            "apple color emoji", "segoe ui emoji";
          font-style: normal;
          font-weight: 400;
          word-break: break-all;
          white-space: normal;
          font-size: 12px;
          font-weight: 600;
        }
      }
    }
  }
}
</style>
